package com.mvc.anocation.unti;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.mvc.anocation.Action;
import com.mvc.anocation.Mapping;

public class StrutsAnocation {

	public static Map<String, String> struts_anocation(String path) {
		SAXBuilder builder = new SAXBuilder();
		Map<String, String> map = new HashMap<String, String>();

		try {
			Document document = builder.build(new File(path));
			Element root = document.getRootElement();
			Element e = root.getChild("search");
			String[] packages = e.getAttributeValue("package").split(",");
			List<Class<?>> list = new ArrayList<Class<?>>();
			String classpath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
			for (String pack : packages) {
				File file = new File(classpath + pack.replace(".", "/"));
				File[] files = file.listFiles();
				for (File f : files) {
					if (!f.isDirectory()) {
						try {
							String fname = f.getName().substring(0, f.getName().lastIndexOf("."));
							// 返回扫描的包里的所有文件的全路径
							list.add(Class.forName(pack + "." + fname));
						} catch (ClassNotFoundException ex) {
							ex.printStackTrace();
						}
					}
				}
			}

			for (Class<?> clazz : list) {
				// 判断类上是否有Annotation
				if (clazz.isAnnotationPresent(Action.class)) {
					Action req_class = (Action) clazz.getAnnotation(Action.class);
					Method[] methods = clazz.getMethods();
					// 获取所有的反射方法
					for (Method method : methods) {
						Mapping req = method.getAnnotation(Mapping.class);
						if (req != null) {
							StringBuffer paraNames = new StringBuffer();
							// 获取方法的参数列表
							for (Class<?> para : method.getParameterTypes()) {
								paraNames.append("," + para.getName());
								System.out.println(paraNames.toString());
							}
							String url = req.value();
							map.put("/" + url, clazz.getName() + "||" + method.getName() + "||" + paraNames.substring(1));
						}
					}
				}
			}
			return map;

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;

	}

}
